package com.zhome.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.zhome.gateway.constants.Constants;
import com.zhome.gateway.enums.GateWayCodeEnum;
import com.zhome.gateway.response.GatewayResponse;
import com.zhome.gateway.util.DesEncrypt;
import com.zhome.gateway.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 抽象过滤器。
 * 个人认为，虽然把重复代码抽了出来，但可能不如将这里的方法写在每个具体的Filter中代码可读性高。
 * @author cuiyh9
 * @date 2020/5/12
 */
@Slf4j
public abstract class AbstractZhomeZuulFilter extends ZuulFilter {

    public String gatewayResponseEncrypt(GateWayCodeEnum gateWayCodeEnum) {
        return gatewayResponseEncrypt(gateWayCodeEnum, null);
    }
    public String gatewayResponseEncrypt(GateWayCodeEnum gateWayCodeEnum, Object data) {
        try {
            GatewayResponse gatewayResponse = GatewayResponse.builder()
                    .code(gateWayCodeEnum.getCode())
                    .message(gateWayCodeEnum.getMessage())
                    .requestId(requestId())
                    .data(data)
                    .build();
            return DesEncrypt.encrypt(JsonUtil.toJsonString(gatewayResponse));
        } catch (Exception e) {
            log.error("gatewayResponseEncrypt error", e);
        }
        return null;
    }
    /**
     * 获取请求的唯一标识，即请求的唯一标识
     * @param
     * @return
     */
    public String requestId() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String requestId = (String)ctx.get(Constants.RequestContextKey.CTX_X_REQUEST_ID);
        return requestId;
    }

    /**
     * 设置标识为跳转到类型为post的Filter
     */
    public void setSkipToPostTypeFilter(RequestContext ctx) {
        ctx.put(Constants.RequestContextKey.CTX_X_SUCCESSOR_CAN_EXECUTE, false);
    }

    /**
     * 设置标识为跳转链路中的下一个过滤器
     */
    public void setSkipNextFilter(RequestContext ctx) {
        ctx.put(Constants.RequestContextKey.CTX_X_SUCCESSOR_CAN_EXECUTE, true);
    }

    /**
     * 设置失败响应
     * @param gateWayCode 失败码
     */
    public void setFailResponse(GateWayCodeEnum gateWayCode) {
        RequestContext ctx = RequestContext.getCurrentContext();
        String message = gatewayResponseEncrypt(gateWayCode);
        ctx.setResponseBody(DesEncrypt.encrypt(message));
        ctx.addZuulResponseHeader(Constants.RequestHeader.CONTENT_TYPE, Constants.APPLICATION_JSON);
        ctx.setSendZuulResponse(true);
        ctx.setRouteHost(null);
    }
}
